<?php
/**
 * Grace is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author kiki
 */

namespace Api\InterfaceApi\v2;

use Api\BaseController;
use Api\Middleware\ApiMiddleware;
use Api\Middleware\VerifyInterfaceMiddleware;
use App\Common\Queue\Producer\GraceProducer;
use App\Common\Service\Tool\ConstantsService;
use App\Common\Service\Tool\SmtpService;
use App\Common\Task\GraceTask;
use App\JsonRpc\CalculatorServiceConsumer;
use App\Setting\Service\SettingGenerateTablesService;
use App\System\Mapper\SystemDeptMapper;
use App\System\Mapper\SystemUserMapper;
use App\System\Model\Debug;
use App\System\Model\SystemApi;
use App\System\Model\SystemKikiTest5;
use App\System\Model\SystemKikiUser;
use App\System\Model\SystemQueueLog;
use App\System\Service\SystemKikiTest5Service;
use App\System\Service\SystemMenuService;
use App\System\Service\SystemQueueLogService;
use App\Wms\Request\WmsWmPlawmsTIoRequest;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Exception\ParallelExecutionException;
use Hyperf\Utils\Parallel;
use Mine\Annotation\ApiAuth;
use Mine\Exception\NormalStatusException;
use Mine\Exception\TokenException;
use Mine\Helper\MineCode;
use Yansongda\HyperfPay\Pay;

/**
 * 演示，测试专用
 */
//#[Controller(prefix: "v2/kiki"),ApiAuth,Middleware(ApiMiddleware::class)]
#[Controller(prefix: "v2/test/kiki"),Middleware(ApiMiddleware::class)]
class DemoApiController extends BaseController
{


    /**
     * @var SystemDeptMapper
     */
    protected SystemDeptMapper $dept;

    #[Inject]
    protected SystemKikiTest5Service $kiki5Service;

    #[Inject]
    protected GraceTask $graceTask;

    protected $logger;


    /**
     * 信息表服务
     */
    #[Inject]
    protected SettingGenerateTablesService $tableService;



    #[RequestMapping("test")]
    public function test()
    {

        // elk('test')->info(88);
        // redis()->set('graceServiceKey',true);
        // throw new NormalStatusException(787);
         return $this->success(array_keys(config('logger')));

        // logger('api-access-empty-log')->info('API数据为空，访问日志无法记录，以下为 Request 信息：');

//        $this->validate();
//        $a = [];
//       return $a[1];
//        throw new NormalStatusException('888');
//        return explode(',',$a);
//        $array = [];
//        for ($i = 1; $i < 10; $i++) {
//            $array[] = md5(uniqid());
//        }
//
//        file_put_contents(BASE_PATH . '/runtime/test.txt', 88, FILE_APPEND);
//        sleep(15);
//        file_put_contents(BASE_PATH . '/runtime/test.txt', 77, FILE_APPEND);

//        return $this->success($array);
//        $parallel = new Parallel(5);
//        for ($i = 0; $i < 20; $i++) {
//            $parallel->add(function () {
//                sleep(1);
//                return Coroutine::id();
//            });
//        }
//
//        try{
//            $results = $parallel->wait();
//        } catch(ParallelExecutionException $e){
//            // $e->getResults() 获取协程中的返回值。
//            // $e->getThrowables() 获取协程中出现的异常。
//        }
//        return $results;
//        return 777;

        // lua 脚本
//        $lua = <<<SCRIPT
//   local times = redis.call('get',KEYS[1])
//
//   if  type(times)  == "string" then
//   times = tonumber(times)
//
//   end
//
//   if  times > 0  then
//    redis.call('set',KEYS[1], times - 1)
//    return  times - 1
//
//    end
//
//    return 0
//SCRIPT;
//        $s = redis()->eval($lua, array('name'),1);

//        try {
//            /** @var SystemMenuService $service */
//            $service = make(SystemMenuService::class);
//            debug($service->getTreeList([],false));

//        return Db::select('select id, parent_id,level,name,code,icon,route,component,redirect,is_hidden,type,status,sort,created_at from system_menu');
//        $params['select'] = 'id, parent_id,level,name,code,icon,route,component,redirect,is_hidden,type,status,sort,created_by,created_at,deleted_at';
//        $params['select'] = '*';
//        return $service->getTreeList($params, false);
//        } catch (\Throwable $e) {
//                 debug($e->getMessage());
//        }

//                $container = ApplicationContext::getContainer();
//        $generator = $container->get(IdGeneratorInterface::class);
//        return $generator->generate();
//      $path = BASE_PATH.'/public/uploadfile/20220311/13432387222848.xlsx';
//      return $path;
//        Smtp::email('522402295@qq.com','易购易售发票','发票内容');
//        return 77;
//        return @fsockopen('smtp.qq.com', '25', $errno, $errstr, 10);

//        $this->logger->info("Your log message.");
//        $client = ApplicationContext::getContainer()->get(CalculatorServiceConsumer::class);
//
//        $result = $client->add(10, 2);
//
//        return  $result;
//        throw new TokenException(t('jwt.validate_fail'));
//            throw new NormalStatusException('请先登录', MineCode::TOKEN_EXPIRED);
//        throw new NormalStatusException('请登录11','401');
        // 第二个参数，不进行数据权限检查，否则会拉起检测是否登录。
//        $params = [
//            'userWhere' => 'kiki2'
//        ];
//        $userId = 20;
//        /** @var Jwt $jwt */
//        $jwt = make(Jwt::class);
//        return $jwt->token($userId);
//        redis()->set('kiki',666,100);
//        return SystemKikiUser::query()->find(2)->kiki;
//        Debug::info(api());
//        return $this->kiki5Service->getList();

//        return $this->success([77]);
//        return [\Hyperf\Utils\Coroutine::inCoroutine()];

//        $this->graceTask->push(new GraceProducer('队列测试'),0);

//        $container = ApplicationContext::getContainer();
//        $generator = $container->get(IdGeneratorInterface::class);
//        $id = $generator->generate();
//        return [$id];

//        return $pay->alipay()->web([
//            'out_trade_no' => ''.time(),
//            'total_amount' => '0.01',
//            'subject' => 'yansongda 测试 - 1',
//        ]);

        // 开启5个协程
//        $parallel = new Parallel(5);
//        for ($i = 0; $i < 6; $i++) {
//            $parallel->add(function () {
//                sleep(1);
//                return Coroutine::id();
//            });
//        }
//
//        try{
//            $results = $parallel->wait();
//            return $results;
//        } catch(ParallelExecutionException $e){
//            return $e->getResults();
//            // $e->getThrowables() 获取协程中出现的异常。
//        }

//        return $results;

    }

    #[RequestMapping("code")]
    public function code()
    {
        $id = $this->request->input('id');
        $this->tableService->generate($id);
        return '代码生成完成';
    }


    /**
     * 获取部门列表接口
     * @return array
     */
    public function getDeptList(): array
    {
        // 第二个参数，不进行数据权限检查，否则会拉起检测是否登录。
        return $this->dept->getTreeList([], false);
    }
}